<template>
  <div class="auth-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>授权管理</h2>
    </div>

    <!-- 标签页 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <!-- 用户授权 -->
      <el-tab-pane label="用户授权" name="user-role">
        <div class="user-role-section">
          <el-row :gutter="20">
            <!-- 用户列表 -->
            <el-col :span="8">
              <div class="panel">
                <div class="panel-header">
                  <h4>用户列表</h4>
                  <el-input
                    v-model="userSearchKeyword"
                    placeholder="搜索用户"
                    size="small"
                    @input="handleUserSearch"
                  >
                    <i slot="prefix" class="el-input__icon el-icon-search"></i>
                  </el-input>
                </div>
                <div class="panel-content">
                  <el-tree
                    ref="userTree"
                    :data="userTreeData"
                    :props="userTreeProps"
                    node-key="id"
                    highlight-current
                    @node-click="handleUserClick"
                    :filter-node-method="filterUserNode"
                  />
                </div>
              </div>
            </el-col>

            <!-- 角色选择 -->
            <el-col :span="8">
              <div class="panel">
                <div class="panel-header">
                  <h4>角色选择</h4>
                </div>
                <div class="panel-content">
                  <el-tree
                    ref="roleTree"
                    :data="roleTreeData"
                    :props="roleTreeProps"
                    node-key="id"
                    show-checkbox
                    :default-checked-keys="selectedRoleIds"
                    @check="handleRoleCheck"
                  />
                </div>
              </div>
            </el-col>

            <!-- 权限预览 -->
            <el-col :span="8">
              <div class="panel">
                <div class="panel-header">
                  <h4>权限预览</h4>
                </div>
                <div class="panel-content">
                  <div v-if="selectedUser" class="permission-preview">
                    <div class="user-info">
                      <h5>{{ selectedUser.name }} ({{ selectedUser.username }})</h5>
                    </div>
                    
                    <el-tabs v-model="permissionTab" size="small">
                      <el-tab-pane label="菜单权限" name="menu">
                        <div class="permission-list">
                          <el-tag
                            v-for="permission in menuPermissions"
                            :key="permission.id"
                            size="small"
                            style="margin: 2px;"
                          >
                            {{ permission.permissionName }}
                          </el-tag>
                        </div>
                      </el-tab-pane>
                      <el-tab-pane label="操作权限" name="operation">
                        <div class="permission-list">
                          <el-tag
                            v-for="permission in operationPermissions"
                            :key="permission.id"
                            size="small"
                            type="success"
                            style="margin: 2px;"
                          >
                            {{ permission.permissionName }}
                          </el-tag>
                        </div>
                      </el-tab-pane>
                      <el-tab-pane label="数据权限" name="data">
                        <div class="permission-list">
                          <el-tag
                            v-for="permission in dataPermissions"
                            :key="permission.id"
                            size="small"
                            type="warning"
                            style="margin: 2px;"
                          >
                            {{ permission.permissionName }}
                          </el-tag>
                        </div>
                      </el-tab-pane>
                    </el-tabs>
                  </div>
                  <div v-else class="empty-state">
                    <i class="el-icon-user"></i>
                    <p>请选择用户</p>
                  </div>
                </div>
              </div>
            </el-col>
          </el-row>

          <!-- 操作按钮 -->
          <div class="action-buttons">
            <el-button type="primary" @click="handleSaveUserRoles" :disabled="!selectedUser">
              保存用户角色
            </el-button>
            <el-button @click="handleResetUserRoles" :disabled="!selectedUser">
              重置
            </el-button>
          </div>
        </div>
      </el-tab-pane>

      <!-- 角色授权 -->
      <el-tab-pane label="角色授权" name="role-permission">
        <div class="role-permission-section">
          <el-row :gutter="20">
            <!-- 角色列表 -->
            <el-col :span="8">
              <div class="panel">
                <div class="panel-header">
                  <h4>角色列表</h4>
                  <el-input
                    v-model="roleSearchKeyword"
                    placeholder="搜索角色"
                    size="small"
                    @input="handleRoleSearch"
                  >
                    <i slot="prefix" class="el-input__icon el-icon-search"></i>
                  </el-input>
                </div>
                <div class="panel-content">
                  <el-tree
                    ref="roleListTree"
                    :data="roleListTreeData"
                    :props="roleTreeProps"
                    node-key="id"
                    highlight-current
                    @node-click="handleRoleListClick"
                    :filter-node-method="filterRoleNode"
                  />
                </div>
              </div>
            </el-col>

            <!-- 权限选择 -->
            <el-col :span="8">
              <div class="panel">
                <div class="panel-header">
                  <h4>权限选择</h4>
                </div>
                <div class="panel-content">
                  <el-tree
                    ref="permissionTree"
                    :data="permissionTreeData"
                    :props="permissionTreeProps"
                    node-key="id"
                    show-checkbox
                    :default-checked-keys="selectedPermissionIds"
                    @check="handlePermissionCheck"
                  />
                </div>
              </div>
            </el-col>

            <!-- 权限预览 -->
            <el-col :span="8">
              <div class="panel">
                <div class="panel-header">
                  <h4>权限预览</h4>
                </div>
                <div class="panel-content">
                  <div v-if="selectedRole" class="permission-preview">
                    <div class="role-info">
                      <h5>{{ selectedRole.roleName }} ({{ selectedRole.roleCode }})</h5>
                    </div>
                    
                    <el-tabs v-model="rolePermissionTab" size="small">
                      <el-tab-pane label="菜单权限" name="menu">
                        <div class="permission-list">
                          <el-tag
                            v-for="permission in roleMenuPermissions"
                            :key="permission.id"
                            size="small"
                            style="margin: 2px;"
                          >
                            {{ permission.permissionName }}
                          </el-tag>
                        </div>
                      </el-tab-pane>
                      <el-tab-pane label="操作权限" name="operation">
                        <div class="permission-list">
                          <el-tag
                            v-for="permission in roleOperationPermissions"
                            :key="permission.id"
                            size="small"
                            type="success"
                            style="margin: 2px;"
                          >
                            {{ permission.permissionName }}
                          </el-tag>
                        </div>
                      </el-tab-pane>
                      <el-tab-pane label="数据权限" name="data">
                        <div class="permission-list">
                          <el-tag
                            v-for="permission in roleDataPermissions"
                            :key="permission.id"
                            size="small"
                            type="warning"
                            style="margin: 2px;"
                          >
                            {{ permission.permissionName }}
                          </el-tag>
                        </div>
                      </el-tab-pane>
                    </el-tabs>
                  </div>
                  <div v-else class="empty-state">
                    <i class="el-icon-s-custom"></i>
                    <p>请选择角色</p>
                  </div>
                </div>
              </div>
            </el-col>
          </el-row>

          <!-- 操作按钮 -->
          <div class="action-buttons">
            <el-button type="primary" @click="handleSaveRolePermissions" :disabled="!selectedRole">
              保存角色权限
            </el-button>
            <el-button @click="handleResetRolePermissions" :disabled="!selectedRole">
              重置
            </el-button>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { authApi } from '@/api/authManagement'
import { userApi } from '@/api/userManagement'
import { roleApi } from '@/api/roleManagement'
import { permissionApi } from '@/api/permissionManagement'
import { permissionMixin } from '@/utils/permission'

export default {
  name: 'AuthManagement',
  mixins: [permissionMixin],
  data() {
    return {
      activeTab: 'user-role',
      permissionTab: 'menu',
      rolePermissionTab: 'menu',
      
      // 用户授权相关
      userSearchKeyword: '',
      userTreeData: [],
      selectedUser: null,
      selectedRoleIds: [],
      menuPermissions: [],
      operationPermissions: [],
      dataPermissions: [],
      
      // 角色授权相关
      roleSearchKeyword: '',
      roleListTreeData: [],
      selectedRole: null,
      selectedPermissionIds: [],
      roleMenuPermissions: [],
      roleOperationPermissions: [],
      roleDataPermissions: [],
      
      // 通用数据
      roleTreeData: [],
      permissionTreeData: [],
      
      // 树形组件配置
      userTreeProps: {
        children: 'children',
        label: 'name'
      },
      roleTreeProps: {
        children: 'children',
        label: 'roleName'
      },
      permissionTreeProps: {
        children: 'children',
        label: 'permissionName'
      }
    }
  },
  mounted() {
    this.loadData()
  },
  methods: {
    // 加载数据
    async loadData() {
      await Promise.all([
        this.loadUserTreeData(),
        this.loadRoleTreeData(),
        this.loadPermissionTreeData()
      ])
    },

    // 加载用户树数据
    async loadUserTreeData() {
      try {
        const response = await userApi.getUsers({ page: 1, size: 1000 })
        if (response.code === 200) {
          this.userTreeData = response.data.content.map(user => ({
            id: user.id,
            name: `${user.name} (${user.username})`,
            username: user.username,
            ...user
          }))
        }
      } catch (error) {
        this.$message.error('加载用户数据失败')
      }
    },

    // 加载角色树数据
    async loadRoleTreeData() {
      try {
        const response = await roleApi.getAllRolesTree()
        if (response.code === 200) {
          this.roleTreeData = response.data
          this.roleListTreeData = response.data
        }
      } catch (error) {
        this.$message.error('加载角色数据失败')
      }
    },

    // 加载权限树数据
    async loadPermissionTreeData() {
      try {
        const response = await permissionApi.getAllPermissionsTree()
        if (response.code === 200) {
          this.permissionTreeData = response.data
        }
      } catch (error) {
        this.$message.error('加载权限数据失败')
      }
    },

    // 标签页切换
    handleTabClick(tab) {
      this.activeTab = tab.name
    },

    // 用户搜索
    handleUserSearch() {
      this.$refs.userTree.filter(this.userSearchKeyword)
    },

    // 角色搜索
    handleRoleSearch() {
      this.$refs.roleListTree.filter(this.roleSearchKeyword)
    },

    // 用户节点过滤
    filterUserNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },

    // 角色节点过滤
    filterRoleNode(value, data) {
      if (!value) return true
      return data.roleName.indexOf(value) !== -1
    },

    // 用户点击
    async handleUserClick(data) {
      this.selectedUser = data
      try {
        // 获取用户当前角色
        const roleResponse = await roleApi.getRoles({ page: 1, size: 1000 })
        if (roleResponse.code === 200) {
          const allRoles = this.flattenRoles(roleResponse.data.content)
          const userRoles = allRoles.filter(role => 
            data.roles && data.roles.some(userRole => userRole.id === role.id)
          )
          this.selectedRoleIds = userRoles.map(role => role.id)
          this.$refs.roleTree.setCheckedKeys(this.selectedRoleIds)
        }

        // 获取用户权限预览
        const permissionResponse = await authApi.getUserPermissionPreview(data.id)
        if (permissionResponse.code === 200) {
          const preview = permissionResponse.data
          this.menuPermissions = preview.menuPermissions || []
          this.operationPermissions = preview.operationPermissions || []
          this.dataPermissions = preview.dataPermissions || []
        }
      } catch (error) {
        this.$message.error('加载用户信息失败')
      }
    },

    // 角色列表点击
    async handleRoleListClick(data) {
      this.selectedRole = data
      try {
        // 获取角色当前权限
        const permissionResponse = await roleApi.getRolePermissions(data.id)
        if (permissionResponse.code === 200) {
          this.selectedPermissionIds = permissionResponse.data.map(p => p.id)
          this.$refs.permissionTree.setCheckedKeys(this.selectedPermissionIds)
        }

        // 获取角色权限预览
        const previewResponse = await authApi.getRolePermissionPreview(data.id)
        if (previewResponse.code === 200) {
          const preview = previewResponse.data
          this.roleMenuPermissions = preview.menuPermissions || []
          this.roleOperationPermissions = preview.operationPermissions || []
          this.roleDataPermissions = preview.dataPermissions || []
        }
      } catch (error) {
        this.$message.error('加载角色信息失败')
      }
    },

    // 角色选择变化
    handleRoleCheck(data, checkedInfo) {
      this.selectedRoleIds = checkedInfo.checkedKeys
      this.updateUserPermissionPreview()
    },

    // 权限选择变化
    handlePermissionCheck(data, checkedInfo) {
      this.selectedPermissionIds = checkedInfo.checkedKeys
      this.updateRolePermissionPreview()
    },

    // 更新用户权限预览
    async updateUserPermissionPreview() {
      if (!this.selectedUser) return

      try {
        // 根据选中的角色计算权限
        const allPermissions = this.flattenPermissions(this.permissionTreeData)
        const selectedRoles = this.roleTreeData.filter(role => 
          this.selectedRoleIds.includes(role.id)
        )

        // 这里需要根据实际的角色权限关系来计算
        // 简化处理，直接显示所有权限
        this.menuPermissions = allPermissions.filter(p => p.permissionType === 'menu')
        this.operationPermissions = allPermissions.filter(p => p.permissionType === 'operation')
        this.dataPermissions = allPermissions.filter(p => p.permissionType === 'data')
      } catch (error) {
        console.error('更新权限预览失败:', error)
      }
    },

    // 更新角色权限预览
    async updateRolePermissionPreview() {
      if (!this.selectedRole) return

      try {
        const allPermissions = this.flattenPermissions(this.permissionTreeData)
        const selectedPermissions = allPermissions.filter(p => 
          this.selectedPermissionIds.includes(p.id)
        )

        this.roleMenuPermissions = selectedPermissions.filter(p => p.permissionType === 'menu')
        this.roleOperationPermissions = selectedPermissions.filter(p => p.permissionType === 'operation')
        this.roleDataPermissions = selectedPermissions.filter(p => p.permissionType === 'data')
      } catch (error) {
        console.error('更新权限预览失败:', error)
      }
    },

    // 保存用户角色
    async handleSaveUserRoles() {
      if (!this.selectedUser) {
        this.$message.warning('请选择用户')
        return
      }

      try {
        const response = await authApi.assignRolesToUser({
          userId: this.selectedUser.id,
          roleIds: this.selectedRoleIds
        })
        if (response.code === 200) {
          this.$message.success('用户角色分配成功')
        }
      } catch (error) {
        this.$message.error('用户角色分配失败')
      }
    },

    // 重置用户角色
    handleResetUserRoles() {
      if (this.selectedUser) {
        this.handleUserClick(this.selectedUser)
      }
    },

    // 保存角色权限
    async handleSaveRolePermissions() {
      if (!this.selectedRole) {
        this.$message.warning('请选择角色')
        return
      }

      try {
        const response = await authApi.assignPermissionsToRole({
          roleId: this.selectedRole.id,
          permissionIds: this.selectedPermissionIds
        })
        if (response.code === 200) {
          this.$message.success('角色权限分配成功')
        }
      } catch (error) {
        this.$message.error('角色权限分配失败')
      }
    },

    // 重置角色权限
    handleResetRolePermissions() {
      if (this.selectedRole) {
        this.handleRoleListClick(this.selectedRole)
      }
    },

    // 扁平化角色树
    flattenRoles(roles) {
      let result = []
      roles.forEach(role => {
        result.push(role)
        if (role.children && role.children.length > 0) {
          result = result.concat(this.flattenRoles(role.children))
        }
      })
      return result
    },

    // 扁平化权限树
    flattenPermissions(permissions) {
      let result = []
      permissions.forEach(permission => {
        result.push(permission)
        if (permission.children && permission.children.length > 0) {
          result = result.concat(this.flattenPermissions(permission.children))
        }
      })
      return result
    }
  }
}
</script>

<style scoped>
.auth-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.panel {
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  height: 600px;
  display: flex;
  flex-direction: column;
}

.panel-header {
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.panel-header h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
}

.panel-content {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
}

.permission-preview {
  height: 100%;
}

.user-info, .role-info {
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.user-info h5, .role-info h5 {
  margin: 0;
  font-size: 14px;
  font-weight: 500;
}

.permission-list {
  max-height: 300px;
  overflow-y: auto;
}

.empty-state {
  text-align: center;
  padding: 50px 20px;
  color: #909399;
}

.empty-state i {
  font-size: 48px;
  margin-bottom: 15px;
  display: block;
}

.empty-state p {
  margin: 0;
  font-size: 14px;
}

.action-buttons {
  margin-top: 20px;
  text-align: center;
}

.action-buttons .el-button {
  margin: 0 10px;
}

.user-role-section, .role-permission-section {
  padding: 20px;
  background: #f5f5f5;
  border-radius: 4px;
}
</style>
